package com.qianfeng.teachdemo.fragment;


import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.alibaba.fastjson.JSONObject;
import com.android.volley.AuthFailureError;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.qianfeng.teachdemo.R;
import com.qianfeng.teachdemo.adapter.CommonAdapter;
import com.qianfeng.teachdemo.bean.AppFree;
import com.qianfeng.teachdemo.bean.AppFreeBean;
import com.qianfeng.teachdemo.utils.AppConstant;
import com.qianfeng.teachdemo.utils.VolleyHepler;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;


public class StringRequestFragment extends BaseFragment {
    private ListView listView;
    private CommonAdapter adapter;
    private ArrayList<AppFreeBean> list = new ArrayList<AppFreeBean>();

    public static StringRequestFragment newInstance() {
        StringRequestFragment fragment = new StringRequestFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_string_request, container, false);
        initView(view);
        loadData();
        return view;
    }

    public void initView(View view) {
        listView = (ListView) view.findViewById(R.id.common);
        adapter = new CommonAdapter(activity, list);
        listView.setAdapter(adapter);
    }

    public void loadData() {

        StringRequest request = new StringRequest(AppConstant.freeApi, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                AppFree appFree = JSONObject.parseObject(s, AppFree.class);
                List<AppFreeBean> tempList = appFree.getApplications();
                list.addAll(tempList);
                adapter.notifyDataSetChanged();
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                System.out.println(volleyError.networkResponse.statusCode);
            }
        }) {
            //传递参数
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                return super.getParams();
            }
        };

        //目的 可以随Activity的生命周期联动,方便通过tag来取消任务
        request.setTag(this);
        //设置是否启用缓存
        request.setShouldCache(true);
        VolleyHepler.getInstance().addRequest(request);
    }

    @Override
    public void onStop() {
        super.onStop();
        VolleyHepler.getInstance().getRequestQueue().cancelAll(this);
    }
}
